package cl.ucn.disc.biblio.refcluster;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

import org.apache.log4j.Logger;

public class TextReplacementManager {
	public static final Logger LOGGER = Logger.getLogger(ReferenceClusterer.class.getName());
	

	public Collection<Set<String>> readClusters(File clusterFile) throws FileNotFoundException {
        LOGGER.info("Opening cluster file " + clusterFile);

        Collection<Set<String>> clusters = new LinkedHashSet<Set<String>>();
        Scanner s = new Scanner(clusterFile);

        Set<String> cluster = new LinkedHashSet<String>();
        clusters.add(cluster);
        while (s.hasNextLine()) {
           	String line = s.nextLine();
           	if (line.trim().equals("")) {
                // If the line is empty, it assumes that it is the end of the cluster
                if (s.hasNextLine()) {
                	// If still has more lines
                    cluster = new LinkedHashSet<String>();
                    clusters.add(cluster);
                }
           	} else {
                cluster.add(line.trim().replaceAll("\\s+", " "));
            }
        }
        s.close();
        LOGGER.info("DONE");

        return clusters;		
	}
	
	public Map<String, String> getReplacementsFromClusters(Collection<Set<String>> clusters) {
        LOGGER.info("Defining new names for references");

        Map<String, String> replacements = new LinkedHashMap<String, String>();
        for (Set<String> cluster : clusters) {
            Iterator<String> it = cluster.iterator();
            String replacement = getLongestString(cluster);
            while (it.hasNext()) {
                replacements.put(it.next(), replacement);
            }
        }
        LOGGER.info("DONE");

        return replacements;
	}

	private String getLongestString(Set<String> cluster) {
		String longest = "";
		for (Iterator<String> it = cluster.iterator(); it.hasNext(); ) {
			String str = it.next();
			if (str.length() > longest.length()) {
				longest = str;
			}
		}
		return longest;
	}
	
}
